package com.xhdx.threadpool.tools;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {

    public static void main(String[] args) {
        // 缓存线程池：自动创建线程执行任务，如果线程执行完成任务则保存，供下次使用，如果线程不够则动态创建
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // 表示将完成3个任务量：任务计数器：多线程完成一些列操作
        CountDownLatch ct = new CountDownLatch(3);
        if (ct.getCount() == 3) {
            System.out.println("开始！");
        }

        for (int i = 0; i < 3; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep((long) (Math.random() * 10000));
                        ct.countDown(); // 减1
                        System.out.println(Thread.currentThread().getName() + "准备分任务,剩余任务：" + ct.getCount());

                        // 如果ct计数器不为0则阻塞，为0 则一起执行
                        ct.await();
                        System.out.println(Thread.currentThread().getName() + "完成分任务");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        
        threadPool.shutdown();
        if (ct.getCount() == 0) {
            System.out.println("恭喜，总任务已完成！");
        }
    }
}